// ==================== 门店详情页组件 ====================
const ShopDetailPage = {
    props: ['shop', 'sensors'],
    emits: ['back', 'viewSensor'],
    template: `
        <div class="detail-page">
            <div class="page-header">
                <el-button :icon="ArrowLeft" @click="$emit('back')">返回</el-button>
                <h1><el-icon><Shop /></el-icon> {{ shop.name }}</h1>
            </div>
            
            <!-- 门店基本信息 -->
            <el-card class="info-card">
                <template #header>
                    <span><el-icon><InfoFilled /></el-icon> 基本信息</span>
                </template>
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="门店ID">{{ shop.id }}</el-descriptions-item>
                    <el-descriptions-item label="门店名称">{{ shop.name }}</el-descriptions-item>
                    <el-descriptions-item label="地址" :span="2">{{ shop.address }}</el-descriptions-item>
                    <el-descriptions-item label="负责人">{{ shop.manager || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{ shop.phone || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="创建时间">{{ formatTime(shop.createdAt) }}</el-descriptions-item>
                    <el-descriptions-item label="更新时间">{{ formatTime(shop.updatedAt) }}</el-descriptions-item>
                </el-descriptions>
            </el-card>
            
            <!-- 传感器列表 -->
            <el-card class="info-card" style="margin-top: 20px;">
                <template #header>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span><el-icon><Cpu /></el-icon> 传感器列表 ({{ sensors.length }})</span>
                        <div>
                            <el-tag type="success" size="small" style="margin-right: 10px;">
                                关闭: {{ closedCount }}
                            </el-tag>
                            <el-tag type="warning" size="small" style="margin-right: 10px;">
                                开启: {{ openCount }}
                            </el-tag>
                            <el-tag type="danger" size="small">
                                离线: {{ offlineCount }}
                            </el-tag>
                        </div>
                    </div>
                </template>
                
                <div class="sensors-grid">
                    <div 
                        v-for="sensor in sensors" 
                        :key="sensor.sensorId"
                        class="sensor-card-mini"
                        :class="getSensorCardClass(sensor)"
                        @click="$emit('viewSensor', sensor)"
                    >
                        <div class="sensor-header">
                            <el-icon size="24"><Cpu /></el-icon>
                            <el-tag :type="getStateType(sensor.currentState)" size="small">
                                {{ getStateText(sensor.currentState) }}
                            </el-tag>
                        </div>
                        <div class="sensor-id">{{ sensor.sensorId }}</div>
                        <div class="sensor-location">{{ sensor.location || '未设置位置' }}</div>
                        <div class="sensor-stats">
                            <span class="stat-item">
                                <el-icon><Battery /></el-icon>
                                {{ sensor.batteryLevel || 0 }}%
                            </span>
                            <span class="stat-item">
                                <el-icon><Connection /></el-icon>
                                {{ sensor.rssi || 0 }} dBm
                            </span>
                        </div>
                        <div class="sensor-status">
                            <el-tag :type="sensor.isOffline ? 'danger' : 'success'" size="small">
                                {{ sensor.isOffline ? '离线' : '在线' }}
                            </el-tag>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>
    `,
    setup(props) {
        const { computed } = Vue;
        const { ArrowLeft } = ElementPlusIconsVue;
        
        const closedCount = computed(() => 
            props.sensors.filter(s => s.currentState === 'closed').length
        );
        
        const openCount = computed(() => 
            props.sensors.filter(s => s.currentState === 'open').length
        );
        
        const offlineCount = computed(() => 
            props.sensors.filter(s => s.isOffline).length
        );
        
        const getStateType = (state) => {
            if (state === 'closed') return 'success';
            if (state === 'open') return 'danger';
            return 'info';
        };
        
        const getStateText = (state) => {
            if (state === 'closed') return '已关闭';
            if (state === 'open') return '已开启';
            return '未知';
        };
        
        const getSensorCardClass = (sensor) => {
            if (sensor.isOffline) return 'sensor-card-offline';
            if (sensor.currentState === 'open') return 'sensor-card-open';
            return 'sensor-card-closed';
        };
        
        const formatTime = (time) => {
            if (!time) return '-';
            return new Date(time).toLocaleString('zh-CN');
        };
        
        return {
            ArrowLeft,
            closedCount,
            openCount,
            offlineCount,
            getStateType,
            getStateText,
            getSensorCardClass,
            formatTime,
        };
    }
};

// ==================== 传感器详情页组件 ====================
const SensorDetailPage = {
    props: ['sensor'],
    emits: ['back'],
    template: `
        <div class="detail-page">
            <div class="page-header">
                <el-button :icon="ArrowLeft" @click="$emit('back')">返回</el-button>
                <h1><el-icon><Cpu /></el-icon> 传感器详情</h1>
                <el-tag :type="sensor.isOffline ? 'danger' : 'success'" size="large">
                    {{ sensor.isOffline ? '离线' : '在线' }}
                </el-tag>
            </div>
            
            <!-- 基本信息 -->
            <el-card class="info-card">
                <template #header>
                    <span><el-icon><InfoFilled /></el-icon> 基本信息</span>
                </template>
                <el-descriptions :column="2" border>
                    <el-descriptions-item label="传感器ID">{{ sensor.sensorId }}</el-descriptions-item>
                    <el-descriptions-item label="所属门店">{{ sensor.shopName }}</el-descriptions-item>
                    <el-descriptions-item label="安装位置">{{ sensor.location || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="传感器型号">{{ sensor.sensorModel || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="当前状态">
                        <el-tag :type="getStateType(sensor.currentState)">
                            {{ getStateText(sensor.currentState) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="在线状态">
                        <el-tag :type="sensor.isOffline ? 'danger' : 'success'">
                            {{ sensor.isOffline ? '离线' : '在线' }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="多圈检测">
                        <el-tag :type="sensor.useMultiTurnDetection ? 'success' : 'info'">
                            {{ sensor.useMultiTurnDetection ? '已启用' : '未启用' }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="安装方向">
                        <el-tag :type="getInstallDirectionType(sensor.installDirection)">
                            {{ getInstallDirectionText(sensor.installDirection) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="电池电量">
                        <el-progress 
                            :percentage="sensor.batteryLevel || 0" 
                            :color="getBatteryColor(sensor.batteryLevel)"
                        />
                    </el-descriptions-item>
                    <el-descriptions-item label="信号强度">
                        <span :style="{ color: getSignalColor(sensor.rssi) }">
                            {{ sensor.rssi ? sensor.rssi + ' dBm' : '-' }}
                        </span>
                    </el-descriptions-item>
                    <el-descriptions-item label="最后在线时间">
                        {{ formatTime(sensor.lastOnlineTime) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="最后离线时间">
                        {{ formatTime(sensor.lastOfflineTime) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="创建时间">
                        {{ formatTime(sensor.createdAt) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="更新时间">
                        {{ formatTime(sensor.updatedAt) }}
                    </el-descriptions-item>
                </el-descriptions>
            </el-card>
            
            <!-- 传感器配置 -->
            <el-card class="info-card" style="margin-top: 20px;">
                <template #header>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span><el-icon><Setting /></el-icon> 传感器配置</span>
                        <el-button 
                            type="primary" 
                            size="small" 
                            @click="setCurrentAsBaseline"
                            :loading="baselineLoading"
                        >
                            以当前状态为关闭基准
                        </el-button>
                    </div>
                </template>
                
                <el-form :model="configForm" label-width="120px">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="多圈检测">
                                <el-switch 
                                    v-model="configForm.useMultiTurnDetection" 
                                    @change="updateConfig"
                                    active-text="启用" 
                                    inactive-text="禁用"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="安装方向">
                                <el-select 
                                    v-model="configForm.installDirection" 
                                    @change="updateConfig"
                                    placeholder="请选择安装方向"
                                >
                                    <el-option label="垂直安装" :value="0" />
                                    <el-option label="水平安装" :value="1" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
            
            <!-- 实时数据 -->
            <el-card class="info-card" style="margin-top: 20px;">
                <template #header>
                    <span><el-icon><DataLine /></el-icon> 实时传感器数据</span>
                </template>
                
                <div v-if="realtimeData" class="realtime-data">
                    <div class="data-section">
                        <h3><el-icon><TrendCharts /></el-icon> 欧拉角 (度)</h3>
                        <div class="data-grid">
                            <div class="data-item">
                                <div class="data-label">Pitch (俯仰角)</div>
                                <div class="data-value">{{ formatNumber(realtimeData.pitch) }}°</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">Roll (横滚角)</div>
                                <div class="data-value">{{ formatNumber(realtimeData.roll) }}°</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">Yaw (航向角)</div>
                                <div class="data-value">{{ formatNumber(realtimeData.yaw) }}°</div>
                            </div>
                            <div class="data-item data-item-highlight">
                                <div class="data-label">综合角度</div>
                                <div class="data-value">{{ calculateCompositeAngle() }}°</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 圈数数据 (仅多圈检测模式显示) -->
                    <div v-if="sensor.useMultiTurnDetection" class="data-section">
                        <h3><el-icon><Refresh /></el-icon> 欧拉角圈数</h3>
                        <div class="data-grid">
                            <div class="data-item">
                                <div class="data-label">Pitch 圈数</div>
                                <div class="data-value">{{ formatNumber(realtimeData.pitchTurnCount) }}</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">Roll 圈数</div>
                                <div class="data-value">{{ formatNumber(realtimeData.rollTurnCount) }}</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">Yaw 圈数</div>
                                <div class="data-value">{{ formatNumber(realtimeData.yawTurnCount) }}</div>
                            </div>
                            <div class="data-item data-item-highlight">
                                <div class="data-label">最大圈数</div>
                                <div class="data-value">{{ calculateMaxTurnCount() }}</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="data-section">
                        <h3><el-icon><Odometer /></el-icon> 加速度 (m/s²)</h3>
                        <div class="data-grid">
                            <div class="data-item">
                                <div class="data-label">X轴</div>
                                <div class="data-value">{{ formatNumber(realtimeData.accelX) }}</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">Y轴</div>
                                <div class="data-value">{{ formatNumber(realtimeData.accelY) }}</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">Z轴</div>
                                <div class="data-value">{{ formatNumber(realtimeData.accelZ) }}</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="data-section">
                        <h3><el-icon><Compass /></el-icon> 角速度 (°/s)</h3>
                        <div class="data-grid">
                            <div class="data-item">
                                <div class="data-label">X轴</div>
                                <div class="data-value">{{ formatNumber(realtimeData.gyroX) }}</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">Y轴</div>
                                <div class="data-value">{{ formatNumber(realtimeData.gyroY) }}</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">Z轴</div>
                                <div class="data-value">{{ formatNumber(realtimeData.gyroZ) }}</div>
                            </div>
                            <div class="data-item">
                                <div class="data-label">旋转状态</div>
                                <el-tag :type="realtimeData.isRotating ? 'danger' : 'success'">
                                    {{ realtimeData.isRotating ? '旋转中' : '静止' }}
                                </el-tag>
                            </div>
                        </div>
                    </div>
                    
                    <div class="data-section">
                        <h3><el-icon><Clock /></el-icon> 数据信息</h3>
                        <el-descriptions :column="2" border>
                            <el-descriptions-item label="接收时间">
                                {{ formatTime(realtimeData.receiveTime) }}
                            </el-descriptions-item>
                            <el-descriptions-item label="时间戳">
                                {{ realtimeData.timestamp }}
                            </el-descriptions-item>
                            <el-descriptions-item label="数据包类型">
                                0x{{ realtimeData.packetType ? realtimeData.packetType.toString(16).toUpperCase() : '-' }}
                            </el-descriptions-item>
                            <el-descriptions-item label="订阅标识">
                                0x{{ realtimeData.subscriptionId ? realtimeData.subscriptionId.toString(16).toUpperCase() : '-' }}
                            </el-descriptions-item>
                        </el-descriptions>
                    </div>
                </div>
                
                <el-empty v-else description="暂无实时数据" />
            </el-card>
        </div>
    `,
    setup(props, { emit }) {
        const { ref, reactive, onMounted, onUnmounted } = Vue;
        const { ArrowLeft } = ElementPlusIconsVue;
        
        const realtimeData = ref(null);
        const baselineLoading = ref(false);
        const configForm = reactive({
            useMultiTurnDetection: props.sensor.useMultiTurnDetection || false,
            installDirection: props.sensor.installDirection || 0
        });
        let timer = null;
        
        const loadRealtimeData = async () => {
            try {
                const response = await api.getSensorRealtimeData(props.sensor.sensorId);
                realtimeData.value = response.data;
            } catch (error) {
                console.error('加载实时数据失败:', error);
            }
        };
        
        const calculateCompositeAngle = () => {
            if (!realtimeData.value) return 0;
            const { pitch, roll, yaw } = realtimeData.value;
            if (pitch == null || roll == null || yaw == null) return 0;
            const result = Math.sqrt(
                Math.pow(pitch, 2) + 
                Math.pow(roll, 2) + 
                Math.pow(yaw, 2)
            );
            return result.toFixed(2);
        };
        
        const calculateMaxTurnCount = () => {
            if (!realtimeData.value) return 0;
            const { pitchTurnCount, rollTurnCount, yawTurnCount } = realtimeData.value;
            if (pitchTurnCount == null || rollTurnCount == null || yawTurnCount == null) return 0;
            const max = Math.max(
                Math.abs(pitchTurnCount),
                Math.abs(rollTurnCount), 
                Math.abs(yawTurnCount)
            );
            return max.toFixed(3);
        };
        
        const updateConfig = async () => {
            try {
                await api.updateSensorConfig(props.sensor.sensorId, {
                    useMultiTurnDetection: configForm.useMultiTurnDetection ? 1 : 0,
                    installDirection: configForm.installDirection
                });
                ElMessage.success('配置更新成功');
                // 更新传感器对象
                props.sensor.useMultiTurnDetection = configForm.useMultiTurnDetection;
                props.sensor.installDirection = configForm.installDirection;
            } catch (error) {
                ElMessage.error('配置更新失败: ' + (error.response?.data?.message || error.message));
            }
        };
        
        const setCurrentAsBaseline = async () => {
            try {
                baselineLoading.value = true;
                await api.setCurrentAsBaseline(props.sensor.sensorId);
                ElMessage.success('基准值设置成功');
            } catch (error) {
                ElMessage.error('基准值设置失败: ' + (error.response?.data?.message || error.message));
            } finally {
                baselineLoading.value = false;
            }
        };
        
        const getStateType = (state) => {
            if (state === 'closed') return 'success';
            if (state === 'open') return 'danger';
            return 'info';
        };
        
        const getStateText = (state) => {
            if (state === 'closed') return '已关闭';
            if (state === 'open') return '已开启';
            return '未知';
        };
        
        const getBatteryColor = (level) => {
            if (level >= 60) return '#67c23a';
            if (level >= 30) return '#e6a23c';
            return '#f56c6c';
        };
        
        const getSignalColor = (rssi) => {
            if (!rssi) return '#909399';
            if (rssi >= -60) return '#67c23a';
            if (rssi >= -80) return '#e6a23c';
            return '#f56c6c';
        };
        
        const getInstallDirectionType = (direction) => {
            return direction === 1 ? 'warning' : 'success';
        };
        
        const getInstallDirectionText = (direction) => {
            return direction === 1 ? '水平安装' : '垂直安装';
        };
        
        const formatNumber = (num) => {
            if (num == null) return '-';
            return Number(num).toFixed(2);
        };
        
        const formatTime = (time) => {
            if (!time) return '-';
            return new Date(time).toLocaleString('zh-CN');
        };
        
        onMounted(() => {
            loadRealtimeData();
            timer = setInterval(loadRealtimeData, 3000); // 每3秒刷新
        });
        
        onUnmounted(() => {
            if (timer) clearInterval(timer);
        });
        
        return {
            ArrowLeft,
            realtimeData,
            baselineLoading,
            configForm,
            calculateCompositeAngle,
            calculateMaxTurnCount,
            updateConfig,
            setCurrentAsBaseline,
            getStateType,
            getStateText,
            getBatteryColor,
            getSignalColor,
            getInstallDirectionType,
            getInstallDirectionText,
            formatNumber,
            formatTime,
        };
    }
};

// 导出组件
if (typeof window !== 'undefined') {
    window.ShopDetailPage = ShopDetailPage;
    window.SensorDetailPage = SensorDetailPage;
}

